<template>
	<app-page>
		<wd-config-provider :theme="theme">
			<view class="container" :style="{ height: 'calc(100vh)' }">
				<scroll-view
					:class="['scroll-Y', showUpload ? 'show-upload-list' : '', showBtn([2]) && imType === 'C2C' ? 'in-tips' : '']"
					:scroll-y="true" :scroll-top="scrollTop">
					<!-- 查看更多 -->
					<p v-if="isMore" class="message-more" @click="getHistory">查看更多</p>
					<template v-for="(item, index) in apiMsgList" :id="`tui-${item.ID}`" :key="item.vueForRenderKey">
						<view class="item" v-if="getShow(item)">
							<MessageTimestamp :currTime="item.time"
								:prevTime="index > 0 ? apiMsgList[index - 1].time : 0" />
							<MessageBubble @resendMessage="resendMessage" :messageItem="item"
								:content="item.getMessageContent()">
								<MessageText v-if="item.type === TYPES.MSG_TEXT" :content="item.getMessageContent()" />
								<ProgressMessage v-if="item.type === TYPES.MSG_IMAGE"
									:content="item.getMessageContent()" :messageItem="item">
									<MessageImage :content="item.getMessageContent()" :messageItem="item"
										@previewImage="handleImagePreview(index)" />
								</ProgressMessage>
								<ProgressMessage v-if="item.type === TYPES.MSG_VIDEO"
									:content="item.getMessageContent()" :messageItem="item">
									<MessageVideo :content="item.getMessageContent()" :messageItem="item" />
								</ProgressMessage>
								<ProgressMessage v-if="item.type === TYPES.MSG_AUDIO"
									:content="item.getMessageContent()" :messageItem="item">
									<MessageAudio :content="item.getMessageContent()" :messageItem="item" />
								</ProgressMessage>
								<MessageOrder :flow="item.flow" :content="item.getMessageContent()"
									v-if="item.type === TYPES.MSG_CUSTOM && item.payload.data === 'order'">
								</MessageOrder>
							</MessageBubble>
						</view>
					</template>

				</scroll-view>
				<view :class="['tips', showUpload ? 'show-upload' : '']"
					v-if="platform === 'user' && showBtn([2]) && imType === 'C2C'">
					您购买了电话咨询，如有需要，请点击下方电话图标进行电话咨询。
				</view>
				<view :class="['tips', showUpload ? 'show-upload' : '']"
					v-if="platform !== 'user' && showBtn([2]) && imType === 'C2C'">
					当前用户购买了电话咨询，您可以点击下方电话图标进行电话答疑。
				</view>
				<!-- 输入框 -->
				<view :class="['input-buttom',showUpload ? 'show-upload' : '']" v-if="showBtn() || imType !== 'C2C'">
					<imInput :useruuid="useruuid" @setScrollHeight="setScrollHeight" @setUploadShow="setUploadShow">
					</imInput>
				</view>
				<uploadBox :caseList="caseList" @getAskOrderInfo="getAskOrderInfo" :askOrderInfo="askOrderInfo"
					:useruuid="useruuid" :platform="platform" :isCall="showBtn([2])" @setUploadShow="setUploadShow"
					:showUpload="showUpload">
				</uploadBox>
			</view>
		</wd-config-provider>
	</app-page>
</template>

<script lang="ts">
	import { defineComponent, ref, nextTick, computed, watch } from 'vue';
	import { IMessageModel } from '@tencentcloud/chat-uikit-engine';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import useTencentIm from '../../hooks/useTencentIm';
	import MessageTimestamp from './../components/message-list/message-timestamp.vue';
	import MessageBubble from './../components/message-list/message-bubble.vue';
	import MessageText from './../components/message-list/message-text.vue';
	import MessageImage from './../components/message-list/message-image.vue';
	import MessageVideo from './../components/message-list/message-video.vue';
	import MessageAudio from './../components/message-list/message-audio.vue';
	import ProgressMessage from './../components/message-list/ProgressMessage/index.vue';
	import MessageOrder from './../components/message-list/message-order.vue';
	import imInput from "./../components/im-input.vue"
	import uploadBox from "./../components/upload-box.vue"
	import useStatusHeight from '../../hooks/useStatusHeight';
	import useGetDom from '@/im/useGetDom';
	import { useImStore, useUserStore } from '../../store';
	import { getMsg, getComOrder as getASKOrderInfoApi, getProfileByuuid } from '@/api/index';
	import useRouter from '../../hooks/useRouter';
	import TUIUikitEngine, { TUIConversationService, TUIStore, StoreName } from "@tencentcloud/chat-uikit-engine"
	export default defineComponent({
		name: '',
		components: { MessageTimestamp, MessageBubble, MessageText, MessageImage, MessageVideo, ProgressMessage, MessageOrder, MessageAudio, imInput, uploadBox },
		setup(props, ctx) {
			// 日间light、夜间dark主题
			const theme = ref('light');
			const tencentIM = useTencentIm();
			const statusHeight = useStatusHeight();
			const TYPES = ref(tencentIM.TYPES);
			const imStore = useImStore();
			const userStore = useUserStore();
			const friendInfo : any = ref({});
			let getDom : any = null;
			// #ifdef MP-WEIXIN
			getDom = useGetDom();
			// #endif
			// #ifndef MP-WEIXIN
			getDom = useGetDom(this);
			// #endif
			const router = useRouter();
			const imType = ref('C2C');
			const caseList = ref([]);
			let useruuid = ref('');
			// 是否打开更多组件
			const showUpload = ref(false); // 是否显示上传组件，默认不显示，点击加号按钮时显示，再次点击加号按钮时隐藏。
			// 滚动位置
			const scrollTop = ref<number>(0);
			const askOrderInfo : any = ref({
				ask_type_id: null,
				expire_time: null,
				id: null,
				order_sn: null,
				price: null
			});
			const msgParam = ref({
				page: 1,
			});
			const getAskOrderInfo = async () => {
				let obj = {};
				if (uni.$appConfig.platform === 'user') {
					obj = {
						user_uuid: userStore.uuid,
						lawyer_uuid: useruuid.value
						// imStore.currentConversation.userProfile.userID,
					};
				} else {
					obj = {
						user_uuid: useruuid.value,
						// imStore.currentConversation.userProfile.userID,
						lawyer_uuid: userStore.uuid
					};
				}
				try {
					// TODO 需要注释
					imType.value = 'Case';
					// const res = await getASKOrderInfoApi(obj);
					// if (res.ask_order.length > 0) {
					// 	askOrderInfo.value = res.ask_order;
					// }
					// if (res.anjian_order.length > 0) {
					// 	imType.value = 'Case';
					// 	caseList.value = res.anjian_order;
					// 	// askOrderInfo.value = res.ask_order;
					// }
				} catch (e) {
					//TODO handle the exception
				} finally {
					// 执行一些清理或收尾操作，无论是否发生异常都会执行到这里。
					setScrollHeight();
				}
			};
			const showBtn = (ids = []) => {
				let isOk = false;
				if (askOrderInfo.value.length <= 0 && ids.length <= 0) {
					return false;
				} else if (askOrderInfo.value.length > 0 && ids.length <= 0) {
					return true;
				}
				for (let i = 0; i < askOrderInfo.value.length; i++) {
					let temp : any = askOrderInfo.value[i];
					if (ids.includes(temp.ask_type_id)) {
						isOk = true;
					}
				}
				// TODO 需要注释
				if (imType.value == 'Case') {
					isOk = true;
				}
				return isOk;
			};
			// 设置滚动条位置
			const setScrollHeight = () => {
				nextTick(() => {
					// 滚动到最新一条消息的位置，并触发滚动事件
					try {
						getDom.getDomScroll('.scroll-Y').then((res : any) => {
							if (res && res.scrollHeight) {
								scrollTop.value = res.scrollTop;
								setTimeout(() => {
									scrollTop.value = res.scrollHeight;
								}, 1);
							}
						});
					} catch (e) {
						setTimeout(() => {
							setScrollHeight();
						}, 300);
					}
				});
			};
			// 图片预览
			// 开启图片预览
			const handleImagePreview = (index : number) => {
				if (!apiMsgList) {
					return;
				}
				const imageMessageIndex : number[] = [];
				const imageMessageList : any[] = apiMsgList.value.filter((item, index) => {

					if (!item.isRevoked && !item.hasRiskContent && item.type === TYPES.value.MSG_IMAGE) {
						imageMessageIndex.push(index);
						return true;
					}
					return false;
				});
				uni.previewImage({
					current: imageMessageIndex.indexOf(index),
					urls: imageMessageList.map((message) => message.imgUrl),
					// #ifdef APP-PLUS
					indicator: 'number'
					// #endif
				});
			};
			// 重新发送
			const resendMessage = (e : any) => {
				imStore.resendMessage(e.value);
			};


			// 设置更多展示
			const setUploadShow = () => {
				showUpload.value = !showUpload.value;
				setScrollHeight();
			};

			const platform = computed(() => {
				return uni.$appConfig.platform;
			});
			// 从 imStort 获取 信息
			const messageList = computed(() => {
				return imStore.messageList;
			});
			// 从 imStort 获取 信息加载状态
			const isCompleted = computed(() => {
				return imStore.isCompleted;
			});
			const apiMsgList : any = ref([]);
			const isMore = ref(true);



			// 格式化 通过请求拿来的数据
			const formatApiMsg = (msgList : any) => {
				return msgList.map((item : any) => {
					let temp = JSON.parse(item.msg_content);
					return {
						...item,
						...temp,
						flow: temp.from === imStore.friendUuid ? 'in' : 'out',
						getMessageContent: () => {
							let content = {}
							switch (temp.type) {
								case 'TIMTextElem':
									content = {
										showName: temp.nick,
										text: [{ name: "text", text: temp.payload.text }]
									}
									break;
								case 'TIMSoundElem':
									content = {
										showName: temp.nick,
										second: temp.payload.second,
										url: temp.audioUrl,
									}
									break;
								case 'TIMVideoFileElem':
									content = {
										showName: temp.nick,
										snapshotHeight: temp.payload.snapshotHeight,
										snapshotUrl: temp.videoThumb,
										snapshotWidth: temp.payload.snapshotWidth,
										url: temp.videoUrl,
									}
									break;
								case 'TIMImageElem':
									content = {
										height: temp.payload.imageInfoArray[0].height,
										showName: temp.nick,
										url: temp.imgUrl || temp.payload.imageInfoArray[0].imageUrl,
										width: temp.payload.imageInfoArray[0].width,
									}
									break;
								case 'TIMCustomElem':
									let custom = {
										...temp.payload,
									}
									if (custom.data == 'order') {
										content = {
											businessID: "",
											custom: temp.payload.extension,
											showName: temp.nick,
										};
									}
									break;
								default:
									break;
							}
							return content
						}
					};
				})
			}

			const getHistory = () => {
				msgParam.value.page++;
				getData();
			}

			const getData = () => {
				getMsg({
					party_user_id: imStore.friendUid,
					...msgParam.value,
				}).then((res : any) => {
					let tempList = res.list;
					tempList = formatApiMsg(tempList);
					if (msgParam.value.page > 1) {
						apiMsgList.value = [...tempList, ...apiMsgList.value]
					} else {
						apiMsgList.value = [...tempList]
					}
					if (apiMsgList.value.length >= res.count) {
						isMore.value = false;
					}
					apiMsgList.value = apiMsgList.value.sort((a, b) => {
						let aDate = new Date(a.create_time)
						let bDate = new Date(b.create_time)
						return aDate - bDate
					})

				});
			}
			const setNavigationBarTitle = async () => {
				if (imStore.currentConversationID) {
					const res = await imStore.getConversationProfile();
					if (res.code === 0 && res.data.conversation) {
						uni.setNavigationBarTitle({
							title: res.data.conversation.userProfile.nick
						});

						const userInfo = await getProfileByuuid({
							uuid: res.data.conversation.userProfile.userID
						});
						friendInfo.value = userInfo;
						imStore.toFriendChat(null, userInfo.uid, userInfo.uuid)
					}
				}
			}
			const getShow = (item : any) => {
				if (item.payload.data == 'voice-call' && JSON.parse(item.payload.extension).show == 'false') {
					return false;
				} else {
					return true;
				}
			}
			onLoad((params : any) => {
				if (params.uuid) {
					useruuid.value = params.uuid;
				} else {
					router.back({
						delta: 1
					});
				}
				getData();
				getAskOrderInfo();
				setNavigationBarTitle()
				TUIStore.watch(StoreName.CHAT, {
					newMessageList: (e) => {
						for (let i = 0; i < e.length; i++) {
							let temp = e[i];
							if (temp.from === imStore.friendUuid) {
								apiMsgList.value.push({
									...temp,
									getMessageContent: () => {
										let content = {}
										switch (temp.type) {
											case 'TIMTextElem':
												content = {
													showName: temp.nick,
													text: [{ name: "text", text: temp.payload.text }]
												}
												break;
											case 'TIMSoundElem':
												content = {
													showName: temp.nick,
													second: temp.payload.second,
													url: temp.payload.url,

												}
												break;
											case 'TIMVideoFileElem':
												content = {
													showName: temp.nick,
													snapshotHeight: temp.payload.snapshotHeight,
													snapshotUrl: temp.payload.snapshotUrl,
													snapshotWidth: temp.payload.snapshotWidth,
													url: temp.payload.url,
												}
												break;
											case 'TIMImageElem':
												content = {
													height: temp.payload.imageInfoArray[0].height,
													showName: temp.nick,
													url: temp.payload.imageInfoArray[0].imageUrl,
													width: temp.payload.imageInfoArray[0].width,
												}
												break;
											case 'TIMCustomElem':
												let custom = {
													...temp.payload,
												}
												if (custom.data == 'order') {
													content = {
														businessID: "",
														custom: temp.payload.extension,
														showName: temp.nick,
													};
												}
												break;
											default:
												break;
										}
										return content
									}
								})
								setTimeout(() => {
									setScrollHeight();
								}, 300);
							}
						}
					},
				});
			});
			watch(
				() => imStore.isSending,
				(val, old) => {
					if (val) {
						apiMsgList.value.push(...formatApiMsg([imStore.sendMsgData]))
						imStore.isSending = false;
						setTimeout(() => {
							setScrollHeight();
						}, 300);

					}
				},
				{
					immediate: true,
					deep: true
				}
			);
			watch(
				() => imStore.isInitialized,
				(val, old) => {
					if (val && !imStore.currentConversation) {
						imStore.switchConversation();
						// imStore.watchChat();
						setNavigationBarTitle()
						setTimeout(() => {
							setScrollHeight();
						}, 300);

					}
				},
				{
					immediate: true,
					deep: true
				}
			);


			return {
				theme,
				TYPES,
				useruuid,
				showBtn,
				messageList,
				isCompleted,
				getHistoryMessageList: tencentIM.getHistoryMessageList,
				handleImagePreview,
				showUpload,
				setUploadShow,
				navHeight: statusHeight.navHeight,
				scrollTop,
				resendMessage,
				askOrderInfo,
				platform,
				imType,
				caseList,
				setScrollHeight,
				apiMsgList,
				isMore,
				getHistory,
				getShow,
			};
		}
	});
</script>
<!-- #ifdef MP-WEIXIN -->
<style lang="less">
	page {
		background-color: #f2f2f2;
	}
</style>
<!-- #endif -->
<style lang="less" scoped>
	page {
		background-color: #f2f2f2;
	}

	.wd-popup-order {
		.body {
			padding: 24rpx;

			.wd-cell__value {
				.wd-textarea::after {
					display: none;
				}
			}
		}

		.title {
			font-size: 40rpx;
			font-weight: bold;
			text-align: center;
			padding-bottom: 24rpx;
		}

		.footer {
			margin-top: 24rpx;
		}
	}

	.container {
		height: calc(100%);

		.message-more {
			color: #999;
			cursor: pointer;
			font-size: 14px;
			text-align: center;
			margin-bottom: 24rpx;
		}

		.scroll-Y {
			height: calc(100% - 128rpx - 24rpx);
			padding-top: 24rpx;
		}

		.show-upload-list {
			height: calc(100% - 128rpx - 500rpx);
		}

		.in-tips {
			height: calc(100% - 128rpx - 24rpx - 88rpx);
		}

		.show-upload-list.in-tips {
			height: calc(100% - 128rpx - 500rpx - 88rpx);
		}

		.input-buttom {
			position: fixed;
			bottom: 0;
			width: 100%;
		}

		.tips {
			width: 100%;
			text-align: center;
			font-size: 24rpx;
			color: #fff;
			position: fixed;
			bottom: calc(80rpx + 24rpx + 24rpx);
			padding: 24rpx 0;
			background-color: #c91c1f;
		}



		.show-upload {
			bottom: 500rpx;
		}

		.show-upload.tips {
			bottom: calc(80rpx + 24rpx + 24rpx + 500rpx);
		}


	}
</style>